import { User } from "f2e-middle-rbac/lib/interface"
import type { ActionApp, ActionProfile, ActionTree } from "../../serve/actions"
import { ClientAPI, ServerResult } from "../../serve/interface"

const Fetch = async function (url: string, body?: any, _init: RequestInit = {}) {
    const headers = _init?.headers || {}
    const method = _init.method || ((body || _init.body) ? "POST" : "GET")
    const init: RequestInit = {
        ..._init,
        headers: {
            "Content-Type": "application/json",
            ...headers,
        },
        body: body ? JSON.stringify(body) : _init.body,
        method,
        credentials: "include",
        cache: "no-cache",
    }
    return fetch(url, init).then(res => res.json())
}

export const apis: {
    [key in keyof ActionApp]: ClientAPI<ActionApp[key]>;
} & {
    [key in keyof ActionProfile]: ClientAPI<ActionProfile[key]>;
} & {
    [key in keyof ActionTree]: ClientAPI<ActionTree[key]>;
} = {
    profile: () => Fetch("/api/profile"),
    create_app: (app) => Fetch("/api/create_app", app),
    update_app: (app) => Fetch("/api/update_app", app),
    delete_app: (app) => Fetch("/api/delete_app", app),
    app_init: (app) => Fetch("/api/app_init", app),
    app_detail: (app) => Fetch("/api/app_detail", app),
    save_dir: (body) => Fetch("/api/save_dir", body),
    move_dir: (body) => Fetch("/api/move_dir", body),
    delete_dir: (body) => Fetch("/api/delete_dir", body),
    get_doc: (body) => Fetch("/api/get_doc", body),
    save_doc: (body) => Fetch("/api/save_doc", body),
}

export const api_upload = (file: File, app_id: number): Promise<ServerResult<{url: string}>> => (
    Fetch(`/api/upload?filename=${file.name}&app_id=${app_id || ""}`, null, {
        body: file,
    })
);

export const api_import = (app_id: number, file: File): Promise<ServerResult> => (
    Fetch(`/api/import?app_id=${app_id || ""}`, null, {
        body: file,
    })
);

export const api_users = (): Promise<User[]> => Fetch("/api/all_users", null, { cache: "no-cache" })